import os, pygame
from pygame.locals import *
from tyler import *
import character

def main():

  pygame.init()
  clock = pygame.time.Clock()
  # joystick?
  js_count = pygame.joystick.get_count()
  if( js_count > 0 ):
    # only grab the first one
    joystick = pygame.joystick.Joystick(0)
    joystick.init()
    
  scroll = (0,0) # current top/left scroll point
  viewport = (640,480)
  
  # the display
  screen  = pygame.display.set_mode(viewport)
  # the buffer
  scratch = pygame.Surface((1280,960)).convert()
  
  pygame.display.set_caption('Map Demo')
  pygame.mouse.set_visible(False)
  
  tileEngine = Tyler('testing')
  tileEngine.draw()
  
  layers = tileEngine.getLayers()
  
  # this is where a character will get loaded
  # and tiles etc will be decided based on state
  character_spritesheet = Spritesheet(
    os.path.join('spritesheets','characters.bmp'),'characters')
  all_chars = character_spritesheet.parse(32,-1)
  ch = character.Character(all_chars[29])
  character_sprite = pygame.sprite.RenderUpdates(ch)
  
  # go go speed racer
  try:
    import psyco
    psyco.full()
  except ImportError:
    pass
  
  # the loop
  running = True
  while running:
    for event in pygame.event.get():
      # common event handling
      if event.type == QUIT:
        running = False
      if event.type == KEYDOWN:
        if event.key == K_ESCAPE:
          running = False
      # character event handling
      ch.handle_event(event)
    
    # sprite updating
    character_sprite.update()
      
    # draw to the temporary screen
    scratch.blit( layers[0].surface, (0,0) )        # draw the background
    character_sprite.draw(scratch)                  # draw the sprite layer
    
    # copy from scratch to the actual screen
    top_left = ch.get_scroll(viewport)                      
    screen.blit(scratch,(0,0),(top_left,viewport))  # copy to the actual screen
    
    # flip the display
    pygame.display.flip()
    
    # breathe
    clock.tick(26)
  
if __name__ == '__main__': main()
